package cn.xiaopengstack.domain.agent.service.armory.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.ArmoryCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientApiVO;
import cn.xiaopengstack.domain.agent.service.armory.AbstractArmorySupport;
import cn.xiaopengstack.domain.agent.service.armory.element.RestClientApiChatObserveFilter;
import cn.xiaopengstack.domain.agent.service.armory.factory.DefaultArmoryStrategyFactory;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangyangang
 * AI API对象组装注册节点
 */
@Component
@Slf4j
public class AiClientApiNode extends AbstractArmorySupport {
    @Resource
    private AiClientToolMcpNode aiClientToolMcpNode;

    @Override
    protected String doApply(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        // 构造所有查出来的apiClient并且装载进spring容器中
        List<AiClientApiVO> aiClientApis = dynamicContext.getValue(dataName());
        if (CollectionUtils.isEmpty(aiClientApis)) {
            log.info("AI客户端加载，无可加载的AI API...");
            return router(requestParameter, dynamicContext);
        }

        log.info("AI客户端加载，AI API加载中【{}】", JSONObject.toJSONString(aiClientApis.stream().map(AiClientApiVO::getApiId).collect(Collectors.joining(","))));
        for (AiClientApiVO aiClientApiVO : aiClientApis) {
            // 构造openAiApiClient
            OpenAiApi openAiApi = OpenAiApi.builder()
                    .apiKey(aiClientApiVO.getApiKey())
                    .baseUrl(aiClientApiVO.getBaseUrl())
                    .embeddingsPath(aiClientApiVO.getEmbeddingsPath())
                    .completionsPath(aiClientApiVO.getCompletionsPath())
//                    .restClientBuilder(RestClient.builder().requestInterceptor(new RestClientApiChatObserveFilter()))
                    .build();

            registerBean(beanName(aiClientApiVO.getApiId()), OpenAiApi.class, openAiApi);
        }

        return router(requestParameter, dynamicContext);
    }

    /**
     * 下一个节点
     * 这里是树的分叉点，可以通过逻辑判断来控制下一个执行节点
     * @param requestParameter
     * @param dynamicContext
     * @return
     * @throws Exception
     */
    @Override
    public StrategyHandler<ArmoryCommandEntity, DefaultArmoryStrategyFactory.DynamicContext, String> get(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return aiClientToolMcpNode;
    }

    /**
     * ai_client_api_1234
     * ai_client_api_7890
     * @param id
     * @return
     */
    @Override
    protected String beanName(String id) {
        return AiAgentEnumVO.AI_CLIENT_API.getBeanName(id);
    }

    @Override
    protected String dataName() {
        return AiAgentEnumVO.AI_CLIENT_API.getDataName();
    }
}
